package com.feilong.edgeAI.ui;

import static com.feilong.edgeAI.service.FeiLongService.WAKEUP_STATE;
import static com.feilong.edgeAI.service.FeiLongService.feilongRespone;
import static com.feilong.edgeAI.utils.chat.RawMessage.FromType.AIUI;
import static com.feilong.edgeAI.utils.chat.RawMessage.MsgType.TEXT;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
//import android.support.v4.app.ActivityCompat;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.system.Os;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.aiibt.common.bean.AppVersion;
import com.aiibt.common.core.WDActivity;
import com.aiibt.common.util.Constant;
import com.aiibt.common.util.MD5Utils;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feilong.edgeAI.adapter.CommadClassifyAdapter;
import com.feilong.edgeAI.databinding.ActivityHomeBinding;
import com.feilong.edgeAI.model.AINetRespone;
import com.feilong.edgeAI.model.AIUIMsg;
import com.feilong.edgeAI.model.Commands;
import com.feilong.edgeAI.model.InstallMsg;
import com.feilong.edgeAI.model.MaxMsg;
import com.feilong.edgeAI.model.Oauth;
import com.feilong.edgeAI.model.OauthBase;
import com.feilong.edgeAI.model.PPMessage;
import com.feilong.edgeAI.model.RequestXXZLast;
import com.feilong.edgeAI.model.NetWorkError;
import com.feilong.edgeAI.model.CloseVoice;
import com.feilong.edgeAI.model.CommadClassify;
import com.feilong.edgeAI.model.DownloadProgress;
import com.feilong.edgeAI.model.FloatViewState;
import com.feilong.edgeAI.model.PPInfo;
import com.feilong.edgeAI.model.RequestXXZLastTest;
import com.feilong.edgeAI.model.Setaimode;
import com.feilong.edgeAI.model.ShowDownLoadDialog;
import com.feilong.edgeAI.model.StartAIUI;
import com.feilong.edgeAI.model.StartAskMsg;
import com.feilong.edgeAI.model.StartOnceMsg;
import com.feilong.edgeAI.model.StartTextAIUI;
import com.feilong.edgeAI.model.StopAIUI;
import com.feilong.edgeAI.model.TestUpdate;
import com.feilong.edgeAI.model.TestXxzUpdate;
import com.feilong.edgeAI.model.ToastMsg;
import com.feilong.edgeAI.model.ToggleMsg;
import com.feilong.edgeAI.model.UpInfoDataContentRespone;
import com.feilong.edgeAI.model.UpInfoRespone;
import com.feilong.edgeAI.model.UpdateApp;
import com.feilong.edgeAI.model.UptimeRespone;
import com.feilong.edgeAI.model.UserStopWakeUp;
import com.feilong.edgeAI.service.FeiLongService;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.speech.TTSHelper;
import com.feilong.edgeAI.utils.AppUtils;
import com.feilong.edgeAI.utils.AssetCopy;
import com.feilong.edgeAI.utils.DeviceUtils;
import com.feilong.edgeAI.utils.FileHelper;
import com.feilong.edgeAI.utils.FucUtil;
import com.feilong.edgeAI.utils.NetworkUtil;
import com.feilong.edgeAI.utils.ResultManager;
import com.feilong.edgeAI.utils.chat.RawMessage;
import com.feilong.edgeAI.utils.nlp.StreamNlpResultReorder;
import com.feilong.edgeAI.utils.tts.StreamNlpTtsHelper;
import com.feilong.edgeAI.vm.MainViewModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.iflytek.aikit.core.JLibrary;
import com.iflytek.aiui.AIUIAgent;
import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIEvent;
import com.iflytek.aiui.AIUIListener;
import com.iflytek.aiui.AIUIMessage;
import com.iflytek.aiui.AIUISetting;
import com.iflytek.sparkchain.core.LLM;
import com.iflytek.sparkchain.core.LLMCallbacks;
import com.iflytek.sparkchain.core.LLMConfig;
import com.iflytek.sparkchain.core.LLMError;
import com.iflytek.sparkchain.core.LLMEvent;
import com.iflytek.sparkchain.core.LLMResult;
import com.iflytek.sparkchain.core.Memory;
import com.iflytek.sparkchain.core.SparkChain;
import com.iflytek.sparkchain.core.SparkChainConfig;
import com.ilesson.ppim.ContactCallback;
import com.ilesson.ppim.IPPInterface;
import com.ilesson.ppim.PPFriend;
import com.xuexiang.xui.widget.progress.HorizontalProgressView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import timber.log.Timber;

//import timber.log.Timber;

/** UI更新
 * 主界面类
 * UI
 */
@Route(path = Constant.ACTIVITY_URL_MAIN)
public class HomeActivity extends WDActivity<MainViewModel, ActivityHomeBinding> {


    private static final String TAG = "HomeActivity";
    private static final String AUTHOR_STATUS = "authorization_status";
    public static final String AI_MODE = "ai_mode";
    public static final String AI_TOGGLE = "ai_toggle";
    public static final int ONLINE_AI = 1;
    public static final int OFFLINE_AI = 2;
    private IPPInterface ppService;

    private int mAIUIState = AIUIConstant.STATE_IDLE;
    private boolean mIsValidTTSAudioArrived = false;


    // 当前未结束的结果消息
    private RawMessage mAppendResultMsg = null;
    // 上个大模型结果sid
    private String mLastCbmResultSid = "";

    // 上个stream_nlp结果的sid
    private String mLastStreamNlpSid = "";
    private ResultManager mResultManager;

    // 首个结果的时间
    private long mFirstRespTime;

    // stream_nlp结果重排工具。由于流式结果不一定按顺序到达，所以必须重排
    private StreamNlpResultReorder mStreamNlpResultReorder;

    private String mCurTtsSid = "";
    private AIUIAgent mAIUIAgent = null;
    private boolean mIsWakeupEnable = false;
    private boolean IsTextAIUI = false;

    // 用于stream_nlp结果中的answer合成
    private StreamNlpTtsHelper mStreamNlpTtsHelper;

    private String installString = "";

    private Handler handler = new Handler(Looper.getMainLooper());

    private final StreamNlpTtsHelper.Listener mTtsHelperListener =
            new StreamNlpTtsHelper.Listener() {
                @Override
                public void onText(StreamNlpTtsHelper.OutTextSeg textSeg) {
//                    if (mTTSManager != null) {
                    String addedParams = "tag=" + textSeg.mTag;
                    if (!textSeg.isBegin()) {
                        addedParams = addedParams + ",cancel_last=false";
                    }
//                    EventBus.getDefault().post(new AIUIMsg(textSeg.mText));
//
//                        mTTSManager.startTTS(textSeg.mText, null, false, addedParams);
//                    }
                }

                @Override
                public void onTtsData(JSONObject bizParamJson, byte[] audio) {

                }

                @Override
                public void onFinish(String fullText) {

                }
            };
    private final AIUIListener mAIUIListener = new AIUIListener() {
        @Override
        public void onEvent(AIUIEvent event) {
            Log.i(TAG, "onEvent, eventType=" + event.eventType);

            switch (event.eventType) {
                case AIUIConstant.EVENT_CONNECTED_TO_SERVER: {
                }
                break;

                case AIUIConstant.EVENT_SERVER_DISCONNECTED: {
                }
                break;

                case AIUIConstant.EVENT_WAKEUP: {
                    if (SPUtils.getInstance().getBoolean(WAKEUP_STATE)) {
                        if (!IsTextAIUI) {
                            commonOnWakeup();
                        } else {
                            IsTextAIUI = false;
                        }
                    }
                }
                break;

                case AIUIConstant.EVENT_RESULT: {
                    if (ONLINE_AI == SPUtils.getInstance().getInt(AI_MODE)) {
                        if (SPUtils.getInstance().getBoolean(WAKEUP_STATE)) {
                            processResult(event);
                        }
                    }
                }
                break;

                case AIUIConstant.EVENT_ERROR: {
                    Log.d("aaaaaaaaaaaaaaa", String.valueOf(event.arg1));

                }
                break;

                case AIUIConstant.EVENT_VAD: {
                    if (AIUIConstant.VAD_BOS == event.arg1) {
//                        ToastUtils.showShort("找到vad_bos");
                    } else if (AIUIConstant.VAD_EOS == event.arg1) {
//                        ToastUtils.showShort("找到vad_eos");
                    } else {
//                        ToastUtils.showShort("" + event.arg2);
                    }
                }
                break;

                case AIUIConstant.EVENT_START_RECORD: {
                }
                break;

                case AIUIConstant.EVENT_STOP_RECORD: {
                }
                break;

                case AIUIConstant.EVENT_STATE: {    // 状态事件
                    mAIUIState = event.arg1;
                    if (AIUIConstant.STATE_IDLE == mAIUIState) {
                        // 闲置状态，AIUI未开启
                    } else if (AIUIConstant.STATE_READY == mAIUIState) {
                        // AIUI已就绪，等待唤醒
                    } else if (AIUIConstant.STATE_WORKING == mAIUIState) {
                        // AIUI工作中，可进行交互
                    }
                }
                break;

                case AIUIConstant.EVENT_CMD_RETURN: {
                    if (AIUIConstant.CMD_SYNC == event.arg1) {    // 数据同步的返回
                        int dtype = event.data.getInt("sync_dtype", -1);
                        int retCode = event.arg2;

                        switch (dtype) {
                            case AIUIConstant.SYNC_DATA_SCHEMA: {
                                if (AIUIConstant.SUCCESS == retCode) {

                                } else {

                                }
                            }
                            break;
                        }
                    } else if (AIUIConstant.CMD_QUERY_SYNC_STATUS == event.arg1) {    // 数据同步状态查询的返回
                        // 获取同步类型
                        int syncType = event.data.getInt("sync_dtype", -1);
                        if (AIUIConstant.SYNC_DATA_QUERY == syncType) {
                            // 若是同步数据查询，则获取查询结果，结果中error字段为0则表示上传数据打包成功，否则为错误码
                            String result = event.data.getString("result");

                        }
                    }
                }
                break;

                default: {
                }
                break;
            }
        }
    };

    private StringBuilder sb;
    private boolean sessionFinished = true;
    private LLM llm;
    LLMCallbacks llmCallbacks = new LLMCallbacks() {
        @Override
        public void onLLMResult(LLMResult llmResult, Object usrContext) {
//            showLoadDialog();
            Log.d(TAG, "onLLMResult\n");
            String content = llmResult.getContent();
            Log.e(TAG, "onLLMResult:" + content);
            int status = llmResult.getStatus();
            if (content != null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        chatText.append(content);
//                        toend();
                        sb.append(content);
                    }
                });
            }
            if (usrContext != null) {
                String context = (String) usrContext;
                Log.d(TAG, "context:" + context);
            }
            if (status == 2) {
                int completionTokens = llmResult.getCompletionTokens();
                int promptTokens = llmResult.getPromptTokens();//
                int totalTokens = llmResult.getTotalTokens();
                Log.e(TAG, "completionTokens:" + completionTokens + "promptTokens:" + promptTokens + "totalTokens:" + totalTokens);
                sessionFinished = true;
                returnMsg(sb.toString());
//                dismissloadDialog();
            }

        }

        @Override
        public void onLLMEvent(LLMEvent event, Object usrContext) {
            Log.d(TAG, "onLLMEvent\n");
            Log.w(TAG, "onLLMEvent:" + " " + event.getEventID() + " " + event.getEventMsg());
        }

        @Override
        public void onLLMError(LLMError error, Object usrContext) {
            Log.d(TAG, "onLLMError\n");
            Log.e(TAG, "errCode:" + error.getErrCode() + "errDesc:" + error.getErrMsg());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    chatText.append("错误:" + " err:" + error.getErrCode() + " errDesc:" + error.getErrMsg() + "\n");
                }
            });
            if (usrContext != null) {
                String context = (String) usrContext;
                Log.d(TAG, "context:" + context);
            }
            sessionFinished = true;
        }
    };
    private Dialog loaddialog;


    private void getScreen() {
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int screenHeight = display.getHeight();
        SPUtils.getInstance().put("screenHeight", screenHeight);
//  133      ToastUtils.showShort(screenWidth+" x "+screenHeight);

        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        AppUtils.execCommand("adb shell /system/bin/screencap -p /sdcard/screenshot.png");//截屏


        getScreen();
        if (SPUtils.getInstance().getInt("PrivacyPolicy", 0) == 0) {
            showPrivacyPolicyDialog();
        } else {
            init();
        }
    }

    private void init() {
        if (!SPUtils.getInstance().getBoolean(AUTHOR_STATUS, false)) {
            getOauth();
            return;
        }
        if (!AppUtils.checkIflyFile()) {
            new Thread(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void run() {
                    try {
                        Log.d(TAG, "run: copyFileFromAssets");
                        long start = System.currentTimeMillis();
                        runOnUiThread(() -> showAlert("更新提示", "好的", "正在更新离线翻译资源包", null));
                        AppUtils.copyAssetsDirToSDCard(HomeActivity.this, "diriflytek/itrans/resource", Environment.getExternalStorageDirectory().getPath() + "/.iflytek/itrans");
//                        AppUtils.copyAssetsDirToSDCard(HomeActivity.this, "diriflytek/itrans/resource/nmt_core/encn/e5e1afbaa_1.0.1_encn.res.bin", Environment.getExternalStorageDirectory().getPath()+"/.iflytek/itrans/resource/nmt_core/encn");
                        runOnUiThread(() -> alertDialog.dismiss());
                        ToastUtils.showShort("更新离线翻译已完成");
                        requestPermissions();
                        Log.d(TAG, "run: copyFileFromAssets>>  time=" + (System.currentTimeMillis() - start));
                    } catch (Exception e) {
                        Log.d(TAG, "run: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            })
                    .start()
            ;
        } else {
            requestPermissions();
        }
//        requestPermissions();
//        FileUtil.copyFolderToExternalStorage(this, Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +"diriflytek/", "/data/data/com.feilong.edgeAI/");
        boolean state = SPUtils.getInstance().getBoolean(WAKEUP_STATE, true);
//        File file = new File("/data/data/com.feilong.edgeAI/");
//        if(file.exists()){
//            Log.d(TAG, "onCreate: "+file);
//        }
        binding.switchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.d(TAG, "onCheckedChanged: " + isChecked);
                //binding.voiceIcon.setVisibility(isChecked ? View.VISIBLE : View.GONE);
                EventBus.getDefault().post(new UserStopWakeUp(isChecked));
            }
        });
        binding.switchBtn.setChecked(state);

//        viewModel.requestXXZLastVersionTest(this);
        viewModel.requestAppLastVersion(this, false);//检测app版本更新
//
        viewModel.result.observe(this, new Observer<AppVersion>() {
            @Override
            public void onChanged(AppVersion result) {
                Log.d(TAG, "onChanged:result= " + result);
            }
        });

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (SPUtils.getInstance().getInt(AI_MODE, ONLINE_AI) != ONLINE_AI) {
            binding.radioGroup.check(R.id.radio1);
        } else {
            binding.radioGroup.check(R.id.radio2);
        }

        binding.radioGroup.setOnCheckedChangeListener(onCheckedChangeListener);

        binding.includeOff.findViewById(R.id.rl_remind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeActivity.this,RemindActivity.class));
            }
        });

        bindPPIM();

//        createAgent();
//
//        startVoiceNlp();
//        getUp();

//        createAgent();
//        startVoiceNlp();
        initTermux();
        initSDK();
        initLoadDialog();
    }


    private RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.radio1:
//                    SPUtils.getInstance().put(AI_MODE, ONLINE_AI);
                    SPUtils.getInstance().put(AI_TOGGLE, 0);
                    EventBus.getDefault().post(new Commands("机器人聊天助理"));
                    binding.imgOnline.setVisibility(View.VISIBLE);
                    binding.imgOffline.setVisibility(View.GONE);
                    binding.includeOn.setVisibility(View.VISIBLE);
                    binding.includeOff.setVisibility(View.GONE);
                    binding.voiceIcon.setVisibility(View.GONE);
                    break;
                case R.id.radio2:
//                    SPUtils.getInstance().put(AI_MODE, OFFLINE_AI);
                    SPUtils.getInstance().put(AI_TOGGLE, 1);
                    EventBus.getDefault().post(new Commands("机器人服务助理"));
                    binding.imgOnline.setVisibility(View.GONE);
                    binding.imgOffline.setVisibility(View.VISIBLE);
                    binding.includeOn.setVisibility(View.GONE);
                    binding.includeOff.setVisibility(View.VISIBLE);
                    binding.voiceIcon.setVisibility(View.VISIBLE);
                    break;
//                    case R.id.radio3:
//                        EventBus.getDefault().post(new Commands("翻译功能"));
//                        break;
            }
            EventBus.getDefault().post(new UserStopWakeUp(true));
            binding.switchBtn.setChecked(true);
        }
    };
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ppService = IPPInterface.Stub.asInterface(service);
            if (null == ppService) return;
            try {
                ppService.registerCallback(contactCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            queryAccount();
//            Log.d(TAG, "onServiceConnected: "+pInterface);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    ContactCallback contactCallback = new ContactCallback.Stub() {
        @Override
        public void onLogin(String account) throws RemoteException {
            Log.d(TAG, "onLogin: account=" + account);

        }

        @Override
        public void onLoginOut() throws RemoteException {
            Log.d(TAG, "onLoginOut: ");
        }

        @Override
        public void updateContact(List<PPFriend> list) throws RemoteException {
            for (PPFriend ppFriend : list) {
                Log.d(TAG, "ContactCallback: ppFriend=" + ppFriend);
            }
        }
    };

    /**
     * 绑定智能PP服务
     */
    private void bindPPIM() {
        Intent intentvoice = new Intent();
        intentvoice.setAction("com.ilesson.ppim.service.PPIMService");
        //从 Android 5.0开始 隐式Intent绑定服务的方式已不能使用,所以这里需要设置Service所在服务端的包名
        intentvoice.setPackage("com.ilesson.ppim");
        boolean res = bindService(intentvoice, mConnection, Context.BIND_AUTO_CREATE);
        Log.d(TAG, "bindPPIM: " + res);
    }

    private String account;
    private Map<String, PPFriend> maps = new HashMap<>();

    private void queryAccount() {
        Log.d(TAG, "queryAccount:pInterface= " + ppService);
        if (null != ppService) {
            try {
                account = ppService.getAccount();
                List<PPFriend> list = ppService.getFriends();
                Log.d(TAG, "queryAccount: queryAccount=" + account);
                for (PPFriend ppFriend : list) {
                    maps.put(ppFriend.getName(), ppFriend);
                    Log.d(TAG, "queryAccount: ppFriend=" + ppFriend);
                }

            } catch (RemoteException e) {
//                bindPPIM();
                e.printStackTrace();
            }
        }
    }

    private HorizontalProgressView progressView;
    private AlertDialog dialog;
    private TextView contentView;

    @SuppressLint("NewApi")
    private void showD(String text) {

        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View v = layoutInflater.inflate(R.layout.update_xxz_dialog, null);
        dialog = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
                .setView(v).create();
        contentView = v.findViewById(R.id.update_content);
        contentView.setText(text);
        progressView = v.findViewById(R.id.progress_circular);
        try {
            dialog.show();
            dialog.setView(v, 0, 0, 0, 0);
            dialog.setCancelable(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbindService(mConnection);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }


    //测试下
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Setaimode state) throws RemoteException {
        binding.radioGroup.setOnCheckedChangeListener(null);
        Log.i("AAAAA", "onEventMainThread: sdfadfsdaf");
        if (state.getMode().equals("1")) {//在线聊天
            binding.radioGroup.check(R.id.radio1);
//            SPUtils.getInstance().put(AI_MODE, ONLINE_AI);
            SPUtils.getInstance().put(AI_TOGGLE, 0);

            binding.imgOnline.setVisibility(View.VISIBLE);
            binding.imgOffline.setVisibility(View.GONE);
            binding.includeOn.setVisibility(View.VISIBLE) ;
            binding.includeOff.setVisibility(View.GONE);
            binding.voiceIcon.setVisibility(View.GONE);
        } else if (state.getMode().equals("2")) {//离线机器人功能
            binding.radioGroup.check(R.id.radio2);
//            SPUtils.getInstance().put(AI_MODE, OFFLINE_AI);
            SPUtils.getInstance().put(AI_TOGGLE, 1);
            binding.imgOnline.setVisibility(View.GONE);
            binding.imgOffline.setVisibility(View.VISIBLE);
            binding.includeOn.setVisibility(View.GONE);
            binding.includeOff.setVisibility(View.VISIBLE);
            binding.voiceIcon.setVisibility(View.VISIBLE);
        }
        binding.radioGroup.setOnCheckedChangeListener(onCheckedChangeListener);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(PPMessage ppMessage) throws RemoteException {//给PP好友发信息
        Log.d(TAG, "PPMessage: " + ppMessage);
        boolean ppServiceAlive;
        long delay = 0;
        if (null == ppService) {
            delay = 2000;//ppService被杀或没有初始化，延时发送pp消息
        } else {
            try {
                ppService.getAccount();
                delay = 0;
            } catch (Exception e) {
                delay = 2000;
                bindPPIM();
                e.printStackTrace();
            }
        }
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            public void run() {
                boolean install = AppUtils.isAppInstalled(HomeActivity.this, "com.ilesson.ppim");
                if (install) {
                    PPFriend ppFriend = maps.get(ppMessage.getName());
                    if (null != ppFriend) {
                        ppMessage.setTargetId(ppFriend.getPhone());
                    }
                    AppUtils.startAppByPackageName(HomeActivity.this, "com.ilesson.ppim");
                    Log.d(TAG, "sendMessage: ppService=" + ppService);
                    try {
                        ppService.sendMessage(ppMessage.getType(), account, ppMessage.getTargetId(), ppMessage.getMessage());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                    EventBus.getDefault().post(new AIUIMsg("主人，请您下载AI PP(AI微信，PP聊功能)可以帮您实现！"));
                }
            }

        }, delay);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RequestXXZLast state) throws RemoteException {//更新正式版理解引擎
        viewModel.requestXXZLastVersion(this, false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RequestXXZLastTest state) throws RemoteException {//更新测试版理解引擎
        viewModel.requestXXZLastVersionTest(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NetWorkError state) throws RemoteException {//初始化讯飞网络错误
        showNetError();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FloatViewState state) throws RemoteException {
        if (null != binding.voiceIcon) {
            binding.voiceIcon.setVisibility(state.isShow() ? View.GONE : View.VISIBLE);
            if (OFFLINE_AI == SPUtils.getInstance().getInt(AI_MODE)) {
               // binding.voiceIcon.setVisibility(View.VISIBLE);
            } else {
                binding.voiceIcon.setVisibility(View.GONE);
            }
        }
//        stopVoiceNlp();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadProgress state) throws RemoteException {
        if (null == progressView) {
            return;
        }
        progressView.setProgress(state.getProgress());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ShowDownLoadDialog state) throws RemoteException {
        if (state.isShow()) {
            if (null != dialog && dialog.isShowing() && null != contentView) {
                contentView.setText(state.getText());
                if (!state.getText().equals(getString(R.string.feilong_downloading))) {
                    progressView.setVisibility(View.GONE);
                } else {
                    progressView.setVisibility(View.VISIBLE);
                }
            } else {
                showD(state.getText());
            }
        } else {
            if (null != dialog) {
                dialog.dismiss();
            }
        }
    }

    private void showNetError() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setMessage(R.string.network_error)
                .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setCancelable(false)
                .create().show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TestXxzUpdate state) throws RemoteException {
        viewModel.requestAppLastVersionTest(this, false, true);//更新理解先更新app（测试版）
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UpdateApp state) throws RemoteException {//更新app（测试版）
        viewModel.requestAppLastVersion(this, false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TestUpdate state) throws RemoteException {//更新app（测试版）
        viewModel.requestAppLastVersionTest(this, false, false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CloseVoice state) throws RemoteException {
        Log.d(TAG, "onEventMainThread:CloseVoice " + state);
        binding.switchBtn.setChecked(false);
    }

    private boolean isShowRLChat = false;
    @Override
    protected void initView(Bundle savedInstanceState) {

//        String json = TextUtil.loadJSONFromAsset(this, "main_classify");
        String json = getResources().getString(R.string.main_classify);
        List<CommadClassify> data = new Gson().fromJson(
                json,
                new TypeToken<List<CommadClassify>>() {
                }.getType());
        CommadClassifyAdapter adapter = new CommadClassifyAdapter(this, data);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setAdapter(adapter);

        binding.includeOff.findViewById(R.id.img_chat).setBackgroundResource(R.drawable.shopping_more);
        binding.includeOff.findViewById(R.id.rl_chat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.includeOff.findViewById(R.id.include_chat).setVisibility(isShowRLChat?View.GONE:View.VISIBLE);
                binding.includeOff.findViewById(R.id.img_chat).setBackgroundResource(isShowRLChat?R.drawable.shopping_more:R.drawable.shopping_bottom);
                isShowRLChat = !isShowRLChat;
            }
        });

    }

    private boolean isBind;
    private FeiLongService mBindService;
    private FeiLongService.MyBinder binder;

    private ServiceConnection cnn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isBind = true;
            binder = (FeiLongService.MyBinder) service;// 链接成功后获取到service里的binder实例
            mBindService = binder.getService();// 通过binder获取service实例
            Log.i(TAG, "onServiceConnected");
        }

        // 断开链接的时候调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
            Log.i(TAG, "onServiceDisconnected");
        }
    };

    private void bind() {
        Intent bindIntent = new Intent(this, FeiLongService.class);
        bindService(bindIntent, cnn, BIND_AUTO_CREATE);
    }

    private void requestPermissions() {
        XXPermissions.with(this)
                // 申请安装包权限
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                // 申请悬浮窗权限
                .permission(Permission.SYSTEM_ALERT_WINDOW)
                // 申请通知栏权限
//                .permission(Permission.NOTIFICATION_SERVICE)
                // 申请系统设置权限
                .permission(Permission.WRITE_SETTINGS)
                // 申请单个权限
                .permission(Permission.RECORD_AUDIO)
                .permission(Permission.CALL_PHONE)
                .permission(Permission.READ_PHONE_STATE)
                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .permission(Permission.SEND_SMS)
                .permission(Permission.WRITE_CONTACTS)
                .permission(Permission.READ_CONTACTS)
                .permission(Permission.READ_CONTACTS)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
//                .permission(Manifest.permission.BLUETOOTH_SCAN)
//                .permission(Manifest.permission.BLUETOOTH_ADVERTISE)
//                .permission(Manifest.permission.BLUETOOTH_CONNECT)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
//                        if (all) {

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            startForegroundService(new Intent(HomeActivity.this, FeiLongService.class));
                            Log.d(TAG, "hasPermission:startForegroundService ");
//                            bind();
//                            startForegroundService(new Intent(HomeActivity.this, GuardService.class));
//                            startForegroundService(new Intent(HomeActivity.this, JobWakeUpService.class));
                        } else {
                            startService(new Intent(HomeActivity.this, FeiLongService.class));
//                            startService(new Intent(HomeActivity.this, GuardService.class));
//                            startService(new Intent(HomeActivity.this, JobWakeUpService.class));
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        Log.d(TAG, "noPermission: ");
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult: " + grantResults);
        boolean haspermission = true;
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] == -1) {
                haspermission = false;
                break;
            }
        }
        if (haspermission) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(new Intent(this, FeiLongService.class));
//                startForegroundService(new Intent(this, GuardService.class));
//                startForegroundService(new Intent(this, JobWakeUpService.class));
            } else {
                startService(new Intent(this, FeiLongService.class));
//                startService(new Intent(this, GuardService.class));
//                startService(new Intent(this, JobWakeUpService.class));
            }
        } else {
            finish();
        }

    }

    /**
     * 模拟点击Home键效果，回到桌面
     */
    @Override
    public void onBackPressed() {
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
    }

    private void getOauth() {//飞龙码授权
        if (!NetworkUtil.isNetworkAvailable(this)) {
            showAlert("", getString(R.string.retry), getString(R.string.network_error), () -> getOauth());
            return;
        }
        RequestParams params = new RequestParams(Constant.BASE_URL + "api/oauth/v1.0/flm/token");
        String deviceMd5 = MD5Utils.md5(JLibrary.getInst().getDeviceId());
        Oauth oauth = new Oauth(deviceMd5, "flds_phone", AppUtils.getDeviceName());
        Log.d(TAG, "getOauth: " + params.toString());
        Log.d(TAG, "deviceMd5: " + deviceMd5);
        params.setAsJsonContent(true);
        params.setBodyContent(new Gson().toJson(oauth));
        org.xutils.x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: +" + result);
                OauthBase oauthBase = new Gson().fromJson(result, OauthBase.class);
                if (oauthBase.getCode() == 200) {
                    String text = oauthBase.getData().getApp_secret();
                    String pwd = "029996C79175DCE52408F18EB9A118C8";
                    try {
                        byte[] bs = EncryptUtils.decryptBase64AES(text.getBytes("UTF-8"), pwd.getBytes("UTF-8"), AES_ALGORITHM, null);
                        String decryptText = new String(bs, "UTF-8");
                        Log.d(TAG, "onSuccess: " + decryptText);
                        if (!decryptText.isEmpty() && decryptText.contains(oauthBase.getData().getAppid())) {
                            SPUtils.getInstance().put(AUTHOR_STATUS, true);
                            ToastUtils.showLong(getString(R.string.author_success));
                            requestPermissions();
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else if (oauthBase.getCode() == 6001) {
                    showAlert("", getString(R.string.quit), getString(R.string.no_author_amount), () -> finish());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                cex.printStackTrace();
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private static final String AES_ALGORITHM = "AES/ECB/NoPadding";
    private AlertDialog alertDialog;

    private void showAlert(String title, String ok, String content, MyCallback callback) {
        alertDialog = new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(content)
                .setPositiveButton(ok, (dialogInterface, i) -> callback.onResult())
                .setCancelable(false)
                .create();
        alertDialog.show();
    }

    public interface MyCallback {
        void onResult();
    }

    private void createAgent() {
        if (checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
            return;
        }

        if (null == mAIUIAgent) {
            Log.i(TAG, "createAgent");

            // 为每一个设备设置对应唯一的SN（最好使用设备硬件信息(mac地址，设备序列号等）生成），以便正确统计装机量，避免刷机或者应用卸载重装导致装机量重复计数
            String deviceId = DeviceUtils.getDeviceId(this);
            Log.i(TAG, "deviceId=" + deviceId);

            AIUISetting.setNetLogLevel(AIUISetting.LogLevel.debug);
            AIUISetting.setSystemInfo(AIUIConstant.KEY_SERIAL_NUM, deviceId);

            // 6.6.xxxx.xxxx版本SDK设置用户唯一标识uid（可选，AIUI后台服务需要，不设置则会使用上面的deviceId作为uid）
            // 5.6.xxxx.xxxx版本SDK不能也不需要设置uid
            // AIUISetting.setSystemInfo(AIUIConstant.KEY_UID, deviceId);

            mAIUIAgent = AIUIAgent.createAgent(this, getAIUIParams(), mAIUIListener);
        }

        if (null == mAIUIAgent) {
            final String strErrorTip = "创建AIUIAgent失败！";
            ToastUtils.showShort(strErrorTip);
        } else {
//            ToastUtils.showShort("AIUIAgent已创建");
        }

        // 创建结果重排对象
        mStreamNlpResultReorder = new StreamNlpResultReorder();
        // 文本限制越小界面刷新越频繁
        mStreamNlpResultReorder.setTextMinIncLimit(20);
        // 创建合成管理对象
        mStreamNlpTtsHelper = new StreamNlpTtsHelper(mTtsHelperListener);
        // 文本限制越小越早合成
        mStreamNlpTtsHelper.setTextMinLimit(10);

        // 创建结果管理器
        mResultManager = ResultManager.createInstance();
    }

    private void startVoiceNlp() {
        if (null == mAIUIAgent) {
            ToastUtils.showShort("AIUIAgent为空，请先创建");
            return;
        }

        if (checkCallingOrSelfPermission(Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO});
            return;
        }

        Log.i(TAG, "startVoiceNlp");


        // 先发送唤醒消息，改变AIUI内部状态，只有唤醒状态才能接收语音输入
        // 默认为oneshot模式，即一次唤醒后就进入休眠。可以修改aiui_phone.cfg中speech参数的interact_mode为continuous以支持持续交互
        if (!mIsWakeupEnable) {
            AIUIMessage wakeupMsg = new AIUIMessage(AIUIConstant.CMD_WAKEUP, 0, 0, "", null);
            mAIUIAgent.sendMessage(wakeupMsg);
        }

        // 打开AIUI内部录音机，开始录音。若要使用上传的个性化资源增强识别效果，则在参数中添加pers_param设置
        // 个性化资源使用方法可参见http://doc.xfyun.cn/aiui_mobile/的用户个性化章节
        // 在输入参数中设置tag，则对应结果中也将携带该tag，可用于关联输入输出
        String params = "sample_rate=16000,data_type=audio,pers_param={\"uid\":\"\"},tag=audio-tag";
        AIUIMessage startRecord = new AIUIMessage(AIUIConstant.CMD_START_RECORD, 0, 0, params,
                null);

        mAIUIAgent.sendMessage(startRecord);
    }

    /**
     * 申请权限
     */
    private void requestPermissions(String[] perms) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, perms, 0x0010);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getAIUIParams() {
        String params = FucUtil.readAssetFile(this, "cfg/aiui_phone.cfg", "utf-8");

        try {
            JSONObject paramsJson = new JSONObject(params);
            mIsWakeupEnable = !"off".equals(paramsJson.optJSONObject("speech").optString("wakeup_mode"));
            if (mIsWakeupEnable) {
                FucUtil.copyAssetFolder(this, "ivw", "/sdcard/AIUI/ivw");
            }

            params = paramsJson.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            ;
        }

        return params;
    }

    private void commonOnWakeup() {
        if (ONLINE_AI != SPUtils.getInstance().getInt(AI_MODE)) {
            SPUtils.getInstance().put(AI_MODE, ONLINE_AI);
            EventBus.getDefault().post(new Setaimode("1"));
            EventBus.getDefault().post(new Commands("机器人聊天助理"));
        } else {
//            EventBus.getDefault().post(new ToggleMsg());
        }
//        stopVoiceNlp();
        EventBus.getDefault().post(new AIUIMsg("0"));
    }


    //    private void processResult(AIUIEvent event) {
//        try {
//            JSONObject bizParamJson = new JSONObject(event.info);
//            JSONObject data = bizParamJson.getJSONArray("data").getJSONObject(0);
//            JSONObject params = data.getJSONObject("params");
//            JSONObject content = data.getJSONArray("content").getJSONObject(0);
//
//            long rspTime = event.data.getLong("eos_rslt", -1);  //响应时间
//            String sid = event.data.getString("sid", "");
//            String tag = event.data.getString("tag", "");
//
//            String sub = params.optString("sub");
//            String cnt_id = content.optString("cnt_id");
//
//            if (!"tts".equals(sub)) {
//                if (mLastCbmResultSid != sid) {
//                    mLastCbmResultSid = sid;
//
//                    // 清理之前的结果`
//                    mResultManager.clearSessionResults(5);
//                }
//
//                JSONObject cntJson = new JSONObject(new String(event.data.getByteArray(cnt_id),
//                        "utf-8"));
//                cntJson.put("sid", sid);
//                cntJson.put("eos_rslt", rspTime);
//                Log.d("aaaaaaaaaaaaaaa", "4"+cntJson);
//
//                if ("cbm_semantic".equals(sub)) {
//                    // 从cbm_meta中解析出untrusted字段（为true时表示通用主义结果不可信，应该采用nlp结果）
//                    JSONObject cbmMetaJson = cntJson.optJSONObject("cbm_meta");
//                    JSONObject cbmTextJson = new JSONObject(cbmMetaJson.optString("text"));
//                    JSONObject metaCbmSemanticJson = cbmTextJson.optJSONObject(sub);
//                    boolean untrusted = metaCbmSemanticJson.optBoolean("untrusted", false);
//
//                    // 大模型SDK的通用语义结果
//                    JSONObject semanticJson = cntJson.optJSONObject(sub);
//                    int status = semanticJson.optInt("status", -1);
//                    ResultManager.SubResult subResult = new ResultManager.SubResult(sid, sub,
//                            status,
//                            cntJson);
//                    ResultManager.SessionResult sessionResult = mResultManager.addResult(subResult);
//
//                    if (untrusted) {
//                        // 为true时不处理通用主义结果（不管rc是否为0），应该采用nlp结果
//                        return;
//                    }
//
//                    String text = semanticJson.optString("text", "");
//                    if (!TextUtils.isEmpty(text)) {
//                        try {
//                            JSONObject intentJson = new JSONObject(text);
//                            int rc = intentJson.optInt("rc", -1);
//                            if (rc == 0) {
//                                // 有效语义结果，将语义结果作为消息插入到消息列表中
//                                mAppendResultMsg = new RawMessage(AIUI, TEXT,
//                                        intentJson.toString().getBytes(), null, rspTime);
//                                mAppendResultMsg.service = intentJson.optString("service", "");
//                                mAppendResultMsg.sid = sid;
////                                addChatMessage(mAppendResultMsg);
//                                Log.d("aaaaaaaaaaaaaaa", "4-1"+mAppendResultMsg.cacheContent);
//                                EventBus.getDefault().post(new AIUIMsg(mAppendResultMsg.cacheContent));
//
//                                // 设置标记
//                                sessionResult.mHasValidSemantic = true;
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                } else if ("nlp".equals(sub)) {
//                    if (!cntJson.has("nlp")) {
//                        // AIUI v1的通用语义结果
//                        JSONObject intentJson = cntJson.optJSONObject("intent");
//                        if (intentJson.length() != 0) {
//                            // 解析得到语义结果，将语义结果作为消息插入到消息列表中
//                            RawMessage rawMessage = new RawMessage(AIUI, TEXT,
//                                    intentJson.toString().getBytes(), null, rspTime);
////                            addChatMessage(rawMessage);
//                            Log.d("aaaaaaaaaaaaaaa", "4-2"+rawMessage.cacheContent);
//                            EventBus.getDefault().post(new AIUIMsg(rawMessage.cacheContent));
//                        }
//                    } else {
//
//                        // AIUI v2的结果
//                        // 解析出索引，状态和文本字段
//                        JSONObject nlpJson = cntJson.optJSONObject("nlp");
//                        int seq = nlpJson.getInt("seq");
//                        int status = nlpJson.getInt("status");
//                        String text = nlpJson.getString("text");
//
//                        if (text.startsWith("{\"intent\":")) {
//                            // AIUI通用语义结果
//                            JSONObject textJson = new JSONObject(text);
//                            JSONObject intentJson = textJson.optJSONObject("intent");
//                            JSONObject answertext = new JSONObject(intentJson.toString());
//                            JSONObject answerJsontext = answertext.optJSONObject("answer");
//                            JSONObject conntextobj = new JSONObject(answerJsontext.toString());
//                            String conntext=conntextobj.getString("text");
//                            if (intentJson.length() != 0) {
//                                // 解析得到语义结果，将语义结果作为消息插入到消息列表中
//                                RawMessage rawMessage = new RawMessage(AIUI, TEXT,
//                                        intentJson.toString().getBytes(), null, rspTime);
////                                addChatMessage(rawMessage);
//                                Log.d("aaaaaaaaaaaaaaa", "4-3"+conntext);
//                                EventBus.getDefault().post(new AIUIMsg(conntext.toString()));
//                            }
//                        } else {
//                            // 大模型语义结果
//                            ResultManager.SubResult subResult = new ResultManager.SubResult(sid, sub,
//                                    status, cntJson);
//                            ResultManager.SessionResult sessionResult =
//                                    mResultManager.addResult(subResult);
//
//                            if (sessionResult.mHasValidSemantic) {
//                                ResultManager.ResultStream resultStream =
//                                        sessionResult.getResultStream("nlp");
//                                if (resultStream.mIsCompleted) {
//                                    // 把同一个sid下的结果更新到消息中
//                                    JSONArray allResults = sessionResult.getSubResultJsonArray();
//                                    mAppendResultMsg.setMsgData(allResults.toString().getBytes());
//
////                                    updateChatMessage(mAppendResultMsg);
//                                    Log.d("aaaaaaaaaaaaaaa", "4-4"+mAppendResultMsg.cacheContent);
//                                    EventBus.getDefault().post(new AIUIMsg(mAppendResultMsg.cacheContent));
//                                }
//
//                                return;
//                            }
//
//                            if (!mLastStreamNlpSid.equals(sid)) {
//                                mFirstRespTime = rspTime;
//                                mLastStreamNlpSid = sid;
//
//                                // 来了新结果，清空之前
//                                mStreamNlpResultReorder.clear();
//                                mStreamNlpTtsHelper.clear();
//                                mAppendResultMsg = null;
//                            }
//
//                            mStreamNlpTtsHelper.addText(text, seq, status);
//
//
//
//                            List<StreamNlpResultReorder.StreamNlpResult> addedResultList =
//                                    mStreamNlpResultReorder.addResult(new StreamNlpResultReorder.StreamNlpResult(cntJson,
//                                            text, seq, status));
//                            if (addedResultList != null) {
//                                String orderedText = mStreamNlpResultReorder.getOrderedText();
//                                if (mAppendResultMsg == null) {
//                                    JSONObject firstResult = addedResultList.get(0).mIntentJson;
//                                    int rc = firstResult.optInt("rc", 0);
//                                    String service = firstResult.optString("service", "");
//
//                                    mAppendResultMsg = new RawMessage(AIUI, TEXT, null,
//                                            orderedText, mFirstRespTime);
//                                    mAppendResultMsg.rc = rc;
//                                    mAppendResultMsg.service = service;
//                                    mAppendResultMsg.sid = sid;
//
////                                    addChatMessage(mAppendResultMsg);
//                                    Log.d("aaaaaaaaaaaaaaa", "4-5"+mAppendResultMsg.cacheContent);
//                                    EventBus.getDefault().post(new AIUIMsg(mAppendResultMsg.cacheContent));
//                                } else {
//                                    mAppendResultMsg.setCacheContent(orderedText);
//
////                                    updateChatMessage(mAppendResultMsg);
//                                    Log.d("aaaaaaaaaaaaaaa", "4-6"+mAppendResultMsg.cacheContent);
//                                    EventBus.getDefault().post(new AIUIMsg(mAppendResultMsg.cacheContent));
//                                }
//
//                                if (mStreamNlpResultReorder.isAddCompleted()) {
//                                    // 结果全部收完
//                                    if (mAppendResultMsg != null) {
////                                    JSONArray allResults =
////                                            mStreamNlpResultReorder.getAllIntentJsonArray();
//
//                                        JSONArray allResults = sessionResult.getSubResultJsonArray();
//                                        mAppendResultMsg.setMsgData(allResults.toString().getBytes());
//
////                                        updateChatMessage(mAppendResultMsg);
//                                        Log.d("aaaaaaaaaaaaaaa", "4-7"+mAppendResultMsg.cacheContent);
//                                        EventBus.getDefault().post(new AIUIMsg(mAppendResultMsg.cacheContent));
//                                    }
//
//                                    mStreamNlpResultReorder.clear();
//                                }
//                            }
//                        }
//                    }
//                } else if ("iat".equals(sub)) {
//                    processIATResult(cntJson);
//                }
//            }else {
//                Log.d("aaaaaaaaaaaaaaa", "4-8");
//                int isUrl = content.optInt("url", 0);
//                if (isUrl == 1) {
//                    Log.d("aaaaaaaaaaaaaaa", "4-9");
//                    Timber.tag(TAG).d("receive tts url: %s",
//                            new String(event.data.getByteArray(cnt_id), "utf-8"));
//                } else {
//                    if (mStreamNlpTtsHelper != null) {
//                        Log.d("aaaaaaaaaaaaaaa", "4-10");
//                        mStreamNlpTtsHelper.onOriginTtsData(tag, bizParamJson, null);
//                    }
//                }
//            }
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }
//    }
    private void processResult(AIUIEvent event) {
        try {
            JSONObject bizParamJson = new JSONObject(event.info);
            JSONObject data = bizParamJson.getJSONArray("data").getJSONObject(0);
            JSONObject params = data.getJSONObject("params");
            JSONObject content = data.getJSONArray("content").getJSONObject(0);

            long rspTime = event.data.getLong("eos_rslt", -1);  //响应时间
            String sid = event.data.getString("sid", "");
            String tag = event.data.getString("tag", "");

            String sub = params.optString("sub");
            String cnt_id = content.optString("cnt_id");

            if (!"tts".equals(sub)) {
                if (mLastCbmResultSid != sid) {
                    mLastCbmResultSid = sid;

                    // 清理之前的结果
                    mResultManager.clearSessionResults(5);
                }

                JSONObject cntJson = new JSONObject(new String(event.data.getByteArray(cnt_id),
                        "utf-8"));
                cntJson.put("sid", sid);
                cntJson.put("eos_rslt", rspTime);
                Log.d("aaaaaaaaaaaaaaa", "4" + cntJson);

                if (cntJson.has("cbm_intent_split")) {
                    JSONObject cbmIntentJson = cntJson.optJSONObject("cbm_intent_split");
                    String asktext = cbmIntentJson.getString("text");
                    JSONObject ask = new JSONObject(asktext.toString());
                    String conntext = ask.getString("query");
                    if (OFFLINE_AI != SPUtils.getInstance().getInt(AI_MODE)) {
                        EventBus.getDefault().post(new StartAskMsg(conntext));
                    }
//                    stopVoiceNlp();
//                    EventBus.getDefault().postSticky(new AIUIMsg("主人你的问题机器人正在计算..\n\n前人种树后人成凉，正是祖先造字的伟大智慧。而造就了世界上人工智能AI理解能力一understand", 6));

                    Log.d("aaaaaaaaaaaaaaa", "4-2----" + conntext);
                }

                if ("cbm_semantic".equals(sub)) {
                    // 从cbm_meta中解析出untrusted字段（为true时表示通用主义结果不可信，应该采用nlp结果）
                    JSONObject cbmMetaJson = cntJson.optJSONObject("cbm_meta");
                    JSONObject cbmTextJson = new JSONObject(cbmMetaJson.optString("text"));
                    JSONObject metaCbmSemanticJson = cbmTextJson.optJSONObject(sub);
                    boolean untrusted = metaCbmSemanticJson.optBoolean("untrusted", false);

                    // 大模型SDK的通用语义结果
                    JSONObject semanticJson = cntJson.optJSONObject(sub);
                    int status = semanticJson.optInt("status", -1);
                    ResultManager.SubResult subResult = new ResultManager.SubResult(sid, sub,
                            status,
                            cntJson);
                    ResultManager.SessionResult sessionResult = mResultManager.addResult(subResult);

                    if (untrusted) {
                        // 为true时不处理通用主义结果（不管rc是否为0），应该采用nlp结果
                        return;
                    }

                    String text = semanticJson.optString("text", "");
                    if (!TextUtils.isEmpty(text)) {
                        try {
                            JSONObject intentJson = new JSONObject(text);
                            int rc = intentJson.optInt("rc", -1);
                            if (rc == 0) {
                                // 有效语义结果，将语义结果作为消息插入到消息列表中
                                mAppendResultMsg = new RawMessage(AIUI, TEXT,
                                        intentJson.toString().getBytes(), null, rspTime);
                                mAppendResultMsg.service = intentJson.optString("service", "");
                                mAppendResultMsg.sid = sid;
//                            addChatMessage(mAppendResultMsg);
                                Log.d("aaaaaaaaaaaaaaa", "4-1" + mAppendResultMsg.cacheContent);
                                // 设置标记
                                sessionResult.mHasValidSemantic = true;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else if ("nlp".equals(sub)) {
                    if (!cntJson.has("nlp")) {
                        // AIUI v1的通用语义结果
                        JSONObject intentJson = cntJson.optJSONObject("intent");
                        if (intentJson.length() != 0) {
                            // 解析得到语义结果，将语义结果作为消息插入到消息列表中
                            RawMessage rawMessage = new RawMessage(AIUI, TEXT,
                                    intentJson.toString().getBytes(), null, rspTime);
//                        addChatMessage(rawMessage);
                            Log.d("aaaaaaaaaaaaaaa", "4-2" + rawMessage.cacheContent);
                        }
                    } else {
                        // AIUI v2的结果
                        // 解析出索引，状态和文本字段
                        JSONObject nlpJson = cntJson.optJSONObject("nlp");
                        int seq = nlpJson.getInt("seq");
                        int status = nlpJson.getInt("status");
                        String text = nlpJson.getString("text");

                        if (text.startsWith("{\"intent\":")) {
                            // AIUI通用语义结果
                            JSONObject textJson = new JSONObject(text);
                            JSONObject intentJson = textJson.optJSONObject("intent");

                            JSONObject answertext = new JSONObject(intentJson.toString());
                            JSONObject answerJsontext = answertext.optJSONObject("answer");
                            JSONObject conntextobj = new JSONObject(answerJsontext.toString());
                            String conntext = conntextobj.getString("text");
                            if (intentJson.length() != 0) {
                                // 解析得到语义结果，将语义结果作为消息插入到消息列表中
                                RawMessage rawMessage = new RawMessage(AIUI, TEXT, intentJson.toString().getBytes(), null, rspTime);
//                              addChatMessage(rawMessage);
                                Log.d("aaaaaaaaaaaaaaa", "4-3" + conntext);
//                                EventBus.getDefault().post(new AIUIMsg(conntext.toString()));
                                returnMsg(conntext);
//                                stopVoiceNlp();
                            }
                        } else {
                            // 大模型语义结果
                            ResultManager.SubResult subResult = new ResultManager.SubResult(sid, sub,
                                    status, cntJson);
                            ResultManager.SessionResult sessionResult =
                                    mResultManager.addResult(subResult);

                            if (sessionResult.mHasValidSemantic) {
                                ResultManager.ResultStream resultStream =
                                        sessionResult.getResultStream("nlp");
                                if (resultStream.mIsCompleted) {
                                    // 把同一个sid下的结果更新到消息中
                                    JSONArray allResults = sessionResult.getSubResultJsonArray();
//                                    mAppendResultMsg.setMsgData(allResults.toString().getBytes());
                                    String resultString = "";
                                    for (int i = 1; i < allResults.length(); i++) {
                                        JSONObject result = new JSONObject(allResults.get(i).toString());
                                        JSONObject nlpJsonObj = result.optJSONObject("nlp");
                                        String tempText = nlpJsonObj.getString("text");
                                        resultString = resultString + tempText;
                                    }

//                                    EventBus.getDefault().post(new AIUIMsg(resultString));
                                    returnMsg(resultString);
//                                    stopVoiceNlp();
//                                    updateChatMessage(mAppendResultMsg);
                                    Log.d("aaaaaaaaaaaaaaa", "4-4" + mAppendResultMsg.msgData + mAppendResultMsg.cacheContent);
                                }

                                return;
                            }

                            if (!mLastStreamNlpSid.equals(sid)) {
                                mFirstRespTime = rspTime;
                                mLastStreamNlpSid = sid;

                                // 来了新结果，清空之前
                                mStreamNlpResultReorder.clear();
                                mStreamNlpTtsHelper.clear();
                                mAppendResultMsg = null;
                            }

                            mStreamNlpTtsHelper.addText(text, seq, status);

                            List<StreamNlpResultReorder.StreamNlpResult> addedResultList = mStreamNlpResultReorder.addResult(new StreamNlpResultReorder.StreamNlpResult(cntJson, text, seq, status));
                            if (addedResultList != null) {
                                String orderedText = mStreamNlpResultReorder.getOrderedText();
                                if (mAppendResultMsg == null) {
                                    JSONObject firstResult = addedResultList.get(0).mIntentJson;
                                    int rc = firstResult.optInt("rc", 0);
                                    String service = firstResult.optString("service", "");

                                    mAppendResultMsg = new RawMessage(AIUI, TEXT, null, orderedText, mFirstRespTime);
                                    mAppendResultMsg.rc = rc;
                                    mAppendResultMsg.service = service;
                                    mAppendResultMsg.sid = sid;

//                                  addChatMessage(mAppendResultMsg);
                                    Log.d("aaaaaaaaaaaaaaa", "4-5" + mAppendResultMsg.cacheContent);
                                } else {
                                    mAppendResultMsg.setCacheContent(orderedText);

//                                  updateChatMessage(mAppendResultMsg);
//                                  EventBus.getDefault().post(new AIUIMsg(mAppendResultMsg.cacheContent));
                                    Log.d("aaaaaaaaaaaaaaa", "4-6" + mAppendResultMsg.cacheContent);
                                }

                                if (mStreamNlpResultReorder.isAddCompleted()) {
                                    // 结果全部收完
                                    if (mAppendResultMsg != null) {
//                                    JSONArray allResults = mStreamNlpResultReorder.getAllIntentJsonArray();

                                        JSONArray allResults = sessionResult.getSubResultJsonArray();
                                        String resultStringM = "";
                                        for (int i = 1; i < allResults.length(); i++) {
                                            JSONObject result = new JSONObject(allResults.get(i).toString());
                                            JSONObject nlpJsonObj = result.optJSONObject("nlp");
                                            String tempText = nlpJsonObj.getString("text");
                                            resultStringM = resultStringM + tempText;
                                        }
                                        mAppendResultMsg.setMsgData(allResults.toString().getBytes());
//                                        EventBus.getDefault().post(new AIUIMsg(resultStringM));
                                        returnMsg(resultStringM);
//                                        stopVoiceNlp();
//                                      updateChatMessage(mAppendResultMsg);
                                        Log.d("aaaaaaaaaaaaaaa", "4-7" + mAppendResultMsg.cacheContent);
                                    }

                                    mStreamNlpResultReorder.clear();
                                }
                            }
                        }
                    }
                } else if ("iat".equals(sub)) {
                    processIATResult(cntJson);
                }
            } else {
                Log.d("aaaaaaaaaaaaaaa", "4-8");
                int isUrl = content.optInt("url", 0);
                if (isUrl == 1) {
                    Log.d("aaaaaaaaaaaaaaa", "4-9");
                    Timber.tag(TAG).d("receive tts url: %s", new String(event.data.getByteArray(cnt_id), "utf-8"));
                } else {
                    if (mStreamNlpTtsHelper != null) {
                        Log.d("aaaaaaaaaaaaaaa", "4-10");
                        mStreamNlpTtsHelper.onOriginTtsData(tag, bizParamJson, null);
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private void returnMsg(String conntext) {
        EventBus.getDefault().post(new AIUIMsg(conntext.toString()));
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (ONLINE_AI == SPUtils.getInstance().getInt(AI_MODE)) {
//                    EventBus.getDefault().post(new AIUIMsg(conntext.toString()));
//                }
//
//            }
//        }, 3000);
    }

    private void processIATResult(JSONObject cntJson) throws JSONException {
//        if (mAppendVoiceMsg == null) return;

        JSONObject text = cntJson.optJSONObject("text");
        // 解析拼接此次听写结果
        StringBuilder iatText = new StringBuilder();
        JSONArray words = text.optJSONArray("ws");
        boolean lastResult = text.optBoolean("ls");
        for (int index = 0; index < words.length(); index++) {
            JSONArray charWord = words.optJSONObject(index).optJSONArray("cw");
            for (int cIndex = 0; cIndex < charWord.length(); cIndex++) {
                iatText.append(charWord.optJSONObject(cIndex).opt("w"));
            }
        }

        String voiceIAT = "";
        String pgsMode = text.optString("pgs");
        //非PGS模式结果
//        if (TextUtils.isEmpty(pgsMode)) {
//            if (TextUtils.isEmpty(iatText)) return;
//
//            //和上一次结果进行拼接
//            if (!TextUtils.isEmpty(mAppendVoiceMsg.cacheContent)) {
//                voiceIAT = mAppendVoiceMsg.cacheContent;//+ "\n";
//            }
//            voiceIAT += iatText;
//        } else {
//            int sn = text.optInt("sn");
//            mIATPGSStack[sn] = iatText.toString();
//            //pgs结果两种模式rpl和apd模式（替换和追加模式）
//            if ("rpl".equals(pgsMode)) {
//                //根据replace指定的range，清空stack中对应位置值
//                JSONArray replaceRange = text.optJSONArray("rg");
//                int start = replaceRange.getInt(0);
//                int end = replaceRange.getInt(1);
//
//                for (int index = start; index <= end; index++) {
//                    mIATPGSStack[index] = null;
//                }
//            }
//
//            StringBuilder PGSResult = new StringBuilder();
//            //汇总stack经过操作后的剩余的有效结果信息
//            for (int index = 0; index < mIATPGSStack.length; index++) {
//                if (TextUtils.isEmpty(mIATPGSStack[index])) continue;
//
////                if(!TextUtils.isEmpty(PGSResult.toString())) PGSResult.append("\n");
//                PGSResult.append(mIATPGSStack[index]);
//                //如果是最后一条听写结果，则清空stack便于下次使用
//                if (lastResult) {
//                    mIATPGSStack[index] = null;
//                }
//            }
//            voiceIAT = join(mInterResultStack) + PGSResult.toString();
//
//            if (lastResult) {
//                mInterResultStack.add(PGSResult.toString());
//            }
//        }
//
//        if (!TextUtils.isEmpty(voiceIAT)) {
//            mAppendVoiceMsg.cacheContent = voiceIAT;
//            updateChatMessage(mAppendVoiceMsg);
//        }
    }

    private String join(List<String> data) {
        StringBuilder builder = new StringBuilder();
        for (int index = 0; index < data.size(); index++) {
            builder.append(data.get(index));
        }

        return builder.toString();
    }

    private void stopVoiceNlp() {
        Log.d("aaaaaaaaaaaaaaa", "99999999999999999");
        if (null == mAIUIAgent) {
            return;
        }

        Log.i(TAG, "stopVoiceNlp");

        // 停止录音
        String params = "sample_rate=16000,data_type=audio";
        AIUIMessage stopRecord = new AIUIMessage(AIUIConstant.CMD_STOP_RECORD, 0, 0, params, null);

        mAIUIAgent.sendMessage(stopRecord);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(StartAIUI aiuiMsg) throws RemoteException {
        Log.d("aaaaaaaaaaaaaaa", "a+++");
//        startVoiceNlp();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(StopAIUI aiuiMsg) throws RemoteException {
//        stopVoiceNlp();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(StartTextAIUI aiuiMsg) throws RemoteException {
        startTextNlp(aiuiMsg.getAIUIMsg());
    }

    private void startTextNlp(String text) {
        if (null == mAIUIAgent) {
            ToastUtils.showShort("AIUIAgent 为空，请先创建");
            return;
        }

        Log.i(TAG, "startTextNlp");

        IsTextAIUI = true;
        AIUIMessage wakeupMsg = new AIUIMessage(AIUIConstant.CMD_WAKEUP, 0, 0, "", null);
        mAIUIAgent.sendMessage(wakeupMsg);

        try {
            // 在输入参数中设置tag，则对应结果中也将携带该tag，可用于关联输入输出
            String params = "data_type=text,tag=text-tag";
            byte[] textData = text.getBytes("utf-8");

            AIUIMessage write = new AIUIMessage(AIUIConstant.CMD_WRITE, 0, 0, params, textData);
            mAIUIAgent.sendMessage(write);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    // 在点击按钮或需要显示对话框的地方调用此方法
    private void showPrivacyPolicyDialog() {
        View customView = getLayoutInflater().inflate(R.layout.privacy_policy_dialog, null);
        Dialog ppdialog = new Dialog(this);
        ppdialog.setContentView(customView);
        ppdialog.setCancelable(false);
        ppdialog.setCanceledOnTouchOutside(false);

        WebView webView = customView.findViewById(R.id.pp_web);
        CheckBox radio = customView.findViewById(R.id.radio1);
        Button btnOk = customView.findViewById(R.id.custom_btn_ok);
        Button btnCancel = customView.findViewById(R.id.custom_btn_cancel);
        btnOk.setOnClickListener(v -> {
                    if (radio.isChecked()) {
                        ppdialog.dismiss();
                        SPUtils.getInstance().put("PrivacyPolicy", 1);

                        init();
                    } else {
                        ToastUtils.showShort("请勾选同意隐私协议");
                    }
                }
        );
        btnCancel.setOnClickListener(v -> {
            finish();
        });
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setTextZoom(50);
        webView.loadUrl("http://private.aiibt.cn:8181/ai_protocol.html");
        ppdialog.show();
    }

    private void showinstallDialog() {
        View customView = getLayoutInflater().inflate(R.layout.instructions_dialog, null);
        Dialog ppdialog = new Dialog(this);
        ppdialog.setContentView(customView);
        ppdialog.setCancelable(false);
        ppdialog.setCanceledOnTouchOutside(false);

        TextView textView = customView.findViewById(R.id.content);
        textView.setText(installString);
        Button btnOk = customView.findViewById(R.id.custom_btn_ok);
        btnOk.setOnClickListener(v -> {
                    installAPK();
                    ppdialog.dismiss();
                }
        );
        ppdialog.show();
    }

    private void initLoadDialog() {
        View customView = getLayoutInflater().inflate(R.layout.load_dialog, null);
        loaddialog = new Dialog(this);
        loaddialog.setContentView(customView);
        loaddialog.setCancelable(false);
        loaddialog.setCanceledOnTouchOutside(false);

    }

    private void showLoadDialog() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                loaddialog.show();
            }
        });

    }

    private void dismissloadDialog() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                loaddialog.dismiss();
            }
        });

    }


    private void initTermux() {
        if (AppUtils.isIntallTermux(this)) {

        } else {
            getIntallTime();
        }
    }

    private void openFileManager() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");  // 设置文件类型为任意类型
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
    }


    private Callback.Cancelable cancelable;

    private Callback.Cancelable Upcancelable;

    private void getIntallTime() {
        RequestParams params = new RequestParams(Constant.TALK_NET_URL + "uptime");
        cancelable = org.xutils.x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UptimeRespone uptimeRespone = gson.fromJson(result, UptimeRespone.class);
                installString = uptimeRespone.tips;
                if (uptimeRespone.datetime > uptimeRespone.uptime) {
                    moveTermux();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                cex.printStackTrace();
            }

            @Override
            public void onFinished() {
            }
        });


    }

    private void getUp() {
        RequestParams params = new RequestParams(Constant.TALK_UP_URL + "engine");
        params.addParameter("version", AppUtils.getVersionName(this));
        Upcancelable = org.xutils.x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type listType = new TypeToken<List<UpInfoDataContentRespone>>() {
                }.getType();
                List<UpInfoDataContentRespone> up = gson.fromJson(result, listType);
                Log.e("aaaaaaaaaaaaaaaaa", up.toString());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                cex.printStackTrace();
            }

            @Override
            public void onFinished() {
            }
        });


    }

    private void moveTermux() {
        Context context = this;
        new Thread() {
            @Override
            public void run() {
                try {
                    AssetCopy copy = new AssetCopy(context);
                    try {
                        FileHelper.copyAssetFileToInternalStorage(context, "termux.mp4", "termux.apk");

                        File file = context.getFilesDir();
                        String homePath = new File(file, "").getAbsolutePath();
                        Log.e("aaaaaaaaaaaaaaaaa", homePath);
                        copy.copy("termux.mp4", homePath);

                        File installfile = new File(homePath + "/termux.mp4");
                        Log.e("aaaaaaaaaaaaaaaaa", installfile.getAbsolutePath());
                        if (installfile.exists()) {
//                            moveTaskToBack(true);
//                            showinstallDialog();
//                            FileHelper.renameAssetFile(context, "termux.mp4", "termux.apk");
//                            installAPK();
                            File odlefile = context.getFilesDir(); // 获取内部存储的文件目录
                            File newFile = new File(odlefile, "termux.apk"); // 创建新文件对象
                            try {
                                InputStream is = context.getAssets().open("termux.mp4"); // 打开assets中的原始文件
                                OutputStream os = new FileOutputStream(newFile); // 创建目标文件的输出流

                                byte[] buffer = new byte[1024];
                                int read;
                                while ((read = is.read(buffer)) != -1) {
                                    os.write(buffer, 0, read);
                                }

                                is.close();
                                os.flush();
                                os.close();
                                if (newFile.exists()) {
                                    Log.e("aaaaaaaaaaaaaaaaa", newFile.getAbsolutePath());
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            EventBus.getDefault().post(new InstallMsg());
                                        }
                                    });
//                                    installAPK();
                                }
//                                showinstallDialog();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }


                        } else {

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e("aaaaaaaaaaaaaaa", e.toString());
                    }
                } catch (final Exception e) {
                    Log.e("aaaaaaaaaaaaaaa", e.toString());
                } finally {

                }
            }
        }.start();

//        FileHelper.renameAssetFile(context, "termux.mp4", "termux.apk");

//        openFileManager();
    }


    private void installAPK() {
        File file = new File(this.getFilesDir() + "/termux.apk");
        Uri apkUri = FileProvider.getUriForFile(this, "com.feilong.edgeAI.FileProvider", file);


        Intent intent;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            // Android 11 或更高版本
            intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setData(apkUri);
            // 添加此标志以在应用安装后完成安装过程
            // 请求安装应用
        } else {
            // Android 11 以下版本
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(InstallMsg installMsg) throws RemoteException {
        Log.e("aaaaaaaaaaaaaaaaa", "11111111111111111111");
        showinstallDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Commands command) throws RemoteException {
        if (OFFLINE_AI == SPUtils.getInstance().getInt(AI_MODE)) {
//            stopVoiceNlp();
//            binding.voiceIcon.setVisibility(View.VISIBLE);
        } else {
//            startVoiceNlp();
//            binding.voiceIcon.setVisibility(View.GONE);
            Log.d("aaaaaaaaaaaaaaa", "d+++");
        }
//        EventBus.getDefault().post(new StartOnceMsg());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UserStopWakeUp awake) throws RemoteException {
        SPUtils.getInstance().put(WAKEUP_STATE, awake.getState());
        if (awake.getState()) {
            Log.d("aaaaaaaaaaaaaaa", "b+++");
//            startVoiceNlp();
        } else {
//            stopVoiceNlp();
        }
    }

    private void initSDK() {
        // 初始化SDK，Appid等信息在清单中配置
        SparkChainConfig sparkChainConfig = SparkChainConfig.builder();
        sparkChainConfig.appID("c6dc0413")
                .apiKey("7e14eda8d66bc03642428a8ecaef7498")
                .apiSecret("NjhjYjgyZjlhYTk1ZDY2MDRkMGY3MzVh")//应用申请的appid三元组
                .logLevel(0);

        int ret = SparkChain.getInst().init(getApplicationContext(), sparkChainConfig);
        if (ret == 0) {
            Log.d(TAG, "SDK初始化成功：" + ret);
//            showToast(MainActivity.this, "SDK初始化成功：" + ret);
            setLLMConfig();
        } else {
            Log.d(TAG, "SDK初始化失败：其他错误:" + ret);
//            showToast(MainActivity.this, "SDK初始化失败-其他错误：" + ret);
        }
    }

    private void setLLMConfig() {
        Log.d(TAG, "setLLMConfig");
        LLMConfig llmConfig = LLMConfig.builder();
        llmConfig.domain("generalv3.5");
        llmConfig.url("ws(s)://spark-api.xf-yun.com/v3.5/chat");//必填
        //memory有两种，windows_memory和tokens_memory，二选一即可
        Memory window_memory = Memory.windowMemory(5);
        llm = new LLM(llmConfig, window_memory);

//        Memory tokens_memory = Memory.tokenMemory(8192);
//        llm = new LLM(llmConfig,tokens_memory);

        llm.registerLLMCallbacks(llmCallbacks);
    }

    private void startChat(String msg) {
        if (llm == null) {
            Log.e(TAG, "startChat failed,please setLLMConfig before!");
            return;
        }
        String usrInputText = msg;
        Log.d(TAG, "用户输入：" + usrInputText);

        String myContext = "myContext";

        int ret = llm.arun(usrInputText, myContext);
        if (ret != 0) {
            Log.e(TAG, "SparkChain failed:\n" + ret);
            return;
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
        });

        sessionFinished = false;
        return;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MaxMsg aiuiMsg) throws RemoteException {
        if (sessionFinished) {
            sb = new StringBuilder("");
            startChat(aiuiMsg.aiuiMsg);
            EventBus.getDefault().postSticky(new AIUIMsg("主人你的问题机器人正在计算..\n\n前人种树后人成凉，正是祖先造字的伟大智慧。而造就了世界上人工智能AI理解能力一understand", 6));
        } else {
            EventBus.getDefault().post(new ToastMsg());
        }
    }

}
